/**
 * @param {number[][]} grid
 * @param {number[]} pricing
 * @param {number[]} start
 * @param {number} k
 * @return {number[][]}
 */
 var highestRankedKItems = function(grid, pricing, start, k) {
  const m = grid.length, n = grid[0].length 
  const prices = []
  const [low, high] = pricing
  const dirs = [[0,1],[0,-1],[1,0],[-1,0]]
  let q = [start]
  let step = 0
  const used = new Set()
  while(q.length){
    step++
    let temp = []
    for(let [r,c] of q){
      if(grid[r][c] !== 0){
        if(grid[r][c] >= low && grid[r][c] <= high){
          prices.push([r,c,step])
        }
        for(let [dx, dy] of dirs){
          let x = r+dx, y = c+dy
          if(x >= 0 && x < m && y >= 0 && y < n && !used.has([x,y].toString())){
            temp.push([x,y])
            used.add([x,y].toString())
          }
        }
        used.add([r,c].toString())
      }
    }
    q = temp
  }
  prices.sort((p1,p2) => {
    if(p1[2] !== p2[2]){
      return p1[2] - p2[2]
    }
    let [r1, c1] = [p1[0], p1[1]], [r2, c2] = [p2[0], p2[1]]
    if(grid[r1][c1] !== grid[r2][c2]){
      return grid[r1][c1] - grid[r2][c2]
    }
    if(r1 !== r2) return r1 - r2
    return c1 - c2
  })
  return prices.slice(0, k).map(v => [v[0],v[1]])
};